/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package foxmob.mlts.controller.setter;

import foxmob.mlts.component.FileManager;
import foxmob.mlts.model.QuestionPaper;
import foxmob.mlts.model.Section;
import foxmob.mlts.model.TreeObject;
import foxmob.mlts.viewcontroller.setter.QuestionForm;
import foxmob.mlts.viewcontroller.setter.SectionForm;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author Lunayo
 */
public class SectionFormController extends RootModifyFormController {
    
    private static final String EDIT_LABEL = "Save Section";
    private static final String ADD_LABEL = "Add Section";
    
    private SectionForm delegate;
    
    public SectionFormController(SetterFormController setterFormDelegate,
            SectionForm delegate) {
        super(setterFormDelegate);
        this.delegate = delegate;
    }
    
    public void setDelegate(SectionForm delegate) {
        this.delegate = delegate;
    }
    
    public SectionForm getDelegate() {
        return delegate;
    }
    
    public void fillSectionComponents(TreeObject obj) {
        delegate.getDescriptionText().setText(obj.getSection().getDescription());
        delegate.getSectionText().setText(obj.getSection().getTitle());
        delegate.getTimeText().setText(Integer.toString(obj.getSection().getRemainingSeconds()));
    }
    
    public void eventChanged(SetterFormController.ActionEvent status) {
        if (this.currentState == SetterFormController.ActionEvent.ADD_EVENT) {
            delegate.getSaveButton().setText(ADD_LABEL);
            delegate.getAddSubsectionButton().setVisible(false);
            delegate.getDeleteSectionButton().setVisible(false);
        } else if (this.currentState == SetterFormController.ActionEvent.EDIT_EVENT) {
            delegate.getSaveButton().setText(EDIT_LABEL);
            delegate.getAddSubsectionButton().setVisible(true);
            delegate.getDeleteSectionButton().setVisible(true);
        } 
    }
    
    @Override
    public void setCurrentState(SetterFormController.ActionEvent state) {
        super.setCurrentState(state);
        eventChanged(state);
    }
    
    @Override
    public boolean validateInputComponent() {
        super.validateInputComponent();
        String message =  "Please input all of the information";
        if (delegate.getSectionText().getText().equals("") ||
                delegate.getSectionText().getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, message);
            delegate.getSectionText().requestFocus();
            return false;
        } else if(delegate.getTimeText().getText().equals("") ||
                delegate.getTimeText().getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, message);
            delegate.getTimeText().requestFocus();
            return false;
        } 
        // check if time is number
        try {
            Integer.parseInt(delegate.getTimeText().getText());
        }
        catch (Exception e) {
            message = "Please input only number for time";
            //Not an integer
            JOptionPane.showMessageDialog(null, message);
            delegate.getTimeText().requestFocus();
            return false;
        }
        return true;
    }
    
    @Override
    public void resetInputComponent() {
        super.resetInputComponent();
        delegate.getDescriptionText().setText("");
        delegate.getSectionText().setText("");
        delegate.getTimeText().setText("");
    }
    
    private Section getSectionComponent() {
        Section section = new Section();
        
        section.setDescription(delegate.getDescriptionText().getText());
        section.setTitle(delegate.getSectionText().getText());
        section.setRemainingSeconds(Integer.parseInt(delegate.getTimeText().getText()));
        
        return section;
    }
    
    private void editSectionFromRecord(QuestionPaper record) {
        try {
            // TODO add your handling code here:
            FileManager manager = FileManager.getInstanceObject();
            Section section =
                record.getSectionWithID(treeObject.getSection().getID());;
            Section componentSection = getSectionComponent();
            section.setDescription(componentSection.getDescription());
            section.setRemainingSeconds(componentSection.getRemainingSeconds());
            section.setTitle(componentSection.getTitle());
            record.modifySection(section);
            // Save to file
            manager.saveToFile(record);
            String st ="Section saved successfully!";
            JOptionPane.showMessageDialog(null,st);
        } catch (IOException ex) {
            Logger.getLogger(QuestionForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void addSectionToRecord(QuestionPaper record) {
        // validate input and record exist in data
        if (!validateInputComponent()) {
            return;
        } else if (record.isExistSection(getSectionComponent())) {
            // display message box
            String message = "Record existed, please choose another name";
            JOptionPane.showMessageDialog(null, message);
            return;
        }
        try {
            // TODO add your handling code here:
            FileManager manager = FileManager.getInstanceObject();
            record.addSection(getSectionComponent());
            // Save to file
            manager.saveToFile(record);
            String st ="Section added successfully!";
            JOptionPane.showMessageDialog(null,st);
        } catch (IOException ex) {
            Logger.getLogger(QuestionForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    /**
     * Listener
     */
    
    public void saveButtonDidTap() {
        if (!validateInputComponent()) return;
        if (this.currentState == SetterFormController.ActionEvent.ADD_EVENT) {
            addSectionToRecord(treeObject.getRecord());
            // notify the form the process has finished
            try {
                setterFormDelegate.addTreeDidFinish(getSectionComponent(),
                                            treeObject.getParentNode());
            } catch (Exception e) {
                System.err.print("Error : " + e.getMessage());
            }
            // reset the component
            resetInputComponent();
        } else if (this.currentState == SetterFormController.ActionEvent.EDIT_EVENT) {
            editSectionFromRecord(treeObject.getRecord());
            // notify the form the process has finished
            try {
                setterFormDelegate.editTreeDidFinish(treeObject.getSection(),
                                            treeObject.getParentNode());
            } catch (Exception e) {
                System.err.print("Error: " + e.getMessage());
            }
        }
    }
    
    public void addSubsectionButtonDidTap() {
        try {
            setterFormDelegate.invokeComponent(SetterFormController.ActionEvent.ADD_EVENT);
        } catch (Exception e) {
            System.err.print("Error : " + e.getMessage());
        }
    }
    
    public void deleteSubsectionButtonDidTap() {
        try {
            setterFormDelegate.invokeComponent(SetterFormController.ActionEvent.DELETE_EVENT);
        } catch (Exception e) {
            System.err.print("Error : " + e.getMessage());
        }
        // reset the component
        resetInputComponent();
    }
}
